﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Citrix.XaAdminMobile
{
    /// <summary>
    /// Extension methods for List.
    /// </summary>
    public static class ListExtensions
    {
        /// <summary>
        /// Retrieves the last item from the list.
        /// </summary>
        /// <typeparam name="TSource">The list type</typeparam>
        /// <param name="source">The source list.</param>
        /// <returns>The last item on the list.</returns>
        /// <exception cref="ArgumentNullException">Thrown if the source list is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the list has no items.</exception>
        public static TSource Last<TSource>(this List<TSource> source)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }
            if (source.Count < 1)
            {
                throw new InvalidOperationException("source");
            }

            return source[source.Count - 1];
        }

        /// <summary>
        /// Removes the last item from the list and returns it.
        /// </summary>
        /// <typeparam name="TSource">The list type</typeparam>
        /// <param name="source">The source list.</param>
        /// <returns>The last item on the list.</returns>
        /// <exception cref="ArgumentNullException">Thrown if the source list is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the list has no items.</exception>
        public static TSource Pop<TSource>(this List<TSource> source)
        {
            if (null == source)
            {
                throw new ArgumentNullException("source");
            }
            if (source.Count < 1)
            {
                throw new InvalidOperationException("source");
            }

            var result = source[source.Count - 1];
            source.RemoveAt(source.Count - 1);
            return result;
        }
    }
}
